package com.ktdaddy.config.shiro.realm;

import com.ktdaddy.config.token.JwtToken;
import com.ktdaddy.enums.IsLock;
import com.ktdaddy.pojo.Kernel;
import com.ktdaddy.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Objects;

/**
 * @author kdaddy@163.com
 * @date 2021/4/21 22:23
 */
public class JwtRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RealmHelper realmHelper;

    /**
     * 限定这个 Realm 只处理我们自定义的 JwtToken
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 此处的 SimpleAuthenticationInfo 可返回任意值，密码校验时不会用到它
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken)
            throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authToken;
        if (jwtToken.getPrincipal() == null) {
            throw new AccountException("JWT token参数异常！");
        }
        // 从 JwtToken 中获取当前用户
        String kernelName = jwtToken.getPrincipal().toString();
        // 查询数据库获取用户信息
        Kernel kernel = userService.getKernelByKernelName(kernelName);

        // 用户不存在
        if (Objects.isNull(kernel)) {
            throw new UnknownAccountException("用户不存在！");
        }

        // 用户被锁定
        if (kernel.getIsLock().equals(IsLock.YES.getCode())) {
            throw new LockedAccountException("该用户已被锁定,暂时无法登录！");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(kernel, kernelName, getName());
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return realmHelper.buildCommonInfo();
    }
}
